using System;
using FrameWork;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.InputSystem;
using UnityEngine.Tilemaps;

/// <summary>
/// 玩家动作
/// 玩家使用工具的动作
/// </summary>
public class PlayerAction : MonoBehaviour
{
    [Header("玩家使用锄头/水壶的距离")]
    [SerializeField] private float playerUseToolDistance;
    
    [Header("玩家攻击设置")]
    [SerializeField] private float playerAttackDistance;        // 攻击距离
    [SerializeField] private float playerAttackRayNum;          // 攻击射线数量
    [SerializeField] private float playerAttackRayAngle;        // 攻击角度
    [SerializeField] private LayerMask playerAttackLayerMask;   // 检测图层
    
    [Header("玩家砍树设置")]
    [SerializeField] private float playerAxeDistance;           // 砍树距离
    [SerializeField] private float playerAxeRayNum;             // 砍树射线数量
    [SerializeField] private float playerAxeRayAngle;           // 砍树角度
    [SerializeField] private LayerMask playerAxeLayerMask;      // 检测图层
    
    [Header("玩家采矿设置")]
    [SerializeField] private float playerPickAxeDistance;       // 采矿距离
    [SerializeField] private float playerPickAxeRayNum;         // 采矿射线数量
    [SerializeField] private float playerPickAxeRayAngle;       // 采矿角度
    [SerializeField] private LayerMask playerPickAxeLayerMask;  // 检测图层
    
    // [Header("玩家浇水设置")]
    // [SerializeField] private float playerWaterDistance;         // 浇水距离
    // [SerializeField] private float playerWaterRayNum;           // 浇水射线数量
    // [SerializeField] private float playerWaterRayAngle;         // 浇水角度
    // [SerializeField] private LayerMask playerWaterLayerMask;    // 检测图层
    
    
    private void Start()
    {
        EventSystem.Instance.AddListener(EventName.EVENT_PLAYER_ACTION_USE, UseAction);
    }

    #region Event

    private void UseAction()
    {
        // 判断使用了哪种工具
        switch (Player.Instance.GetCurrentToolKit())
        {
            case PlayerToolkit.Attack:
                HarvestCrop();
                EmittedRay(playerAttackDistance, playerAttackRayNum, playerAttackRayAngle, playerAttackLayerMask);
                break;
            case PlayerToolkit.Axe:
                EmittedRay(playerAxeDistance, playerAxeRayNum, playerAxeRayAngle, playerAxeLayerMask);
                break;
            case PlayerToolkit.Pickaxe:
                EmittedRay(playerPickAxeDistance, playerPickAxeRayNum, playerPickAxeRayAngle, playerPickAxeLayerMask);
                break;
            case PlayerToolkit.Watering:
                // EmittedRay(playerWaterDistance, playerWaterRayNum, playerWaterRayAngle, playerWaterLayerMask);
                Water();
                break;
            case PlayerToolkit.Hoe:
                Hoe();
                break;
        }
    }

    #endregion

    #region EventAction

    /// <summary>
    /// 锄头
    /// </summary>
    private void Hoe()
    {
        // 判断鼠标所处位置是否在规定距离内
        if (!(Vector2.Distance(PlayerInput.Instance.MouseWorldPosition, transform.position) < playerUseToolDistance)) 
            return;
        // print("执行锄地动作");
        EventSystem.Instance.EventTrigger(EventName.EVENT_TILEMAP_CULTIVATETILE, PlayerInput.Instance.MouseWorldPosition);
    }
    
    /// <summary>
    /// 浇水
    /// </summary>
    private void Water()
    {
        // 判断鼠标所处位置是否在规定距离内
        if (!(Vector2.Distance(PlayerInput.Instance.MouseWorldPosition, transform.position) < playerUseToolDistance)) 
            return;
        // print("执行锄地动作");
        EventSystem.Instance.EventTrigger(EventName.EVENT_TILEMAP_WATERCROP, PlayerInput.Instance.MouseWorldPosition);
    }
    
    //
    private void HarvestCrop()
    {
        // 判断鼠标所处位置是否在规定距离内
        if (!(Vector2.Distance(PlayerInput.Instance.MouseWorldPosition, transform.position) < playerUseToolDistance)) 
            return;
        // print("执行锄地动作");
        EventSystem.Instance.EventTrigger(EventName.EVENT_TILEMAP_HARVEST, PlayerInput.Instance.MouseWorldPosition);
    }
    
    /// <summary>
    /// 发射射线
    /// 攻击，砍树，采矿，浇水
    /// </summary>
    private void EmittedRay(float distance, float num, float rayAngle, LayerMask layerMask)
    {
        if (PlayerInput.Instance.Vertical>0.49f && PlayerInput.Instance.Vertical < 0.51f)
        {
            // 向上发射射线
            TakeRay(Vector2.up, distance, num, rayAngle, layerMask);
        }
        else if (PlayerInput.Instance.Vertical > 0.99f)
        {
            // 向下发射射线
            TakeRay(Vector2.down, distance, num, rayAngle, layerMask);
        }
        else
        {
            if (PlayerInput.Instance.Horizontal < 0)
            {
                // 向左发射射线
                TakeRay(Vector2.left, distance, num, rayAngle, layerMask);
            }
            else
            {
                // 向右发射射线
                TakeRay(Vector2.right, distance, num, rayAngle, layerMask);
            }
        }
    }

    #endregion

    #region OtherFunc

    /// <summary>
    /// 发射射线
    /// </summary>
    /// <param name="direction"></param>
    private void TakeRay(Vector2 direction, float distance, float num, float rayAngle, LayerMask layerMask)
    {
        // 计算每次射线之间的角度增量
        float angleIncrement = rayAngle / (num - 1);

        // 计算射线的起始角度
        float startAngle = -rayAngle / 2;

        for (int i = 0; i < num; i++)
        {
            // 计算当前射线的角度
            float currentAngle = startAngle + i * angleIncrement;

            // 将方向向量旋转到当前角度
            Vector2 rayDirection = Quaternion.Euler(0, 0, currentAngle) * direction;
            
            // 执行射线检测
            RaycastHit2D hit = Physics2D.Raycast(transform.position, rayDirection, distance,  layerMask);

            // 如果射线命中目标
            if (hit.collider != null)
            {
                // 获取敌人身上的攻击接口，使用 Attack 函数，传入玩家伤害
                // 用于杀怪，砍树，挖掘石头
                IAttack attack = hit.collider.gameObject.GetComponent<IAttack>();
                if(attack != null)
                    attack.Attack(Player.Instance.GetPlayerDamage());
                
                // 获取NPC身上交互接口
                IInteraction interaction = hit.collider.gameObject.GetComponent<IInteraction>();
                if(interaction != null)
                    interaction.Interact();
                
                // print("玩家当前伤害" + Player.Instance.GetPlayerDamage());
                // print(hit.collider.gameObject.name);
                // 退出循环
                break;
            }

            // 绘制射线（仅用于调试）
            Debug.DrawRay(transform.position, rayDirection * distance, Color.red, 0.5f);
        }
    }

    #endregion
}
